package com.kehutong.crm.worker;

import com.coraframework.quartz.Job;
import com.coraframework.quartz.JobExecutionContext;
import com.coraframework.quartz.JobExecutionException;
import com.kehutong.common.DoveClient;
import com.kehutong.common.errcode.Result;
import com.kehutong.crm.entity.ForecastOpen;
import com.kehutong.crm.enums.DemandForecastTypeEnum;
import com.kehutong.crm.service.DemandForecastService;
import com.kehutong.crm.service.ForecastStatisticsService;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Ioc;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * 需求预测任务
 *
 * @author wupengfei
 */
public class DemandForecastWorker implements Job {

    private static final Logger logger = LoggerFactory.getLogger(DemandForecastWorker.class);
    private static boolean forecastSwitch;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            logger.info("demand forecast work forecastSwitch=" + forecastSwitch);
            forecast();
        } catch (Exception e) {
            logger.error("需求预测定时任务执行时异常", e);
        }
    }

    public static Object forecast() throws Exception {
        if (!forecastSwitch) {
            logger.info("需求预测已关闭");
            return Result.success(forecastSwitch);
        }

        // 获取资源
        DoveClient doveClient = Ioc.getInstance(DoveClient.class);
        DemandForecastService demandForecastService = Ioc.getInstance(DemandForecastService.class);
        ForecastStatisticsService forecastStatisticsService = Ioc.getInstance(ForecastStatisticsService.class);
        JdbcSession jdbcSession = Ioc.getInstance(JdbcSession.class);

        // 获取开放的企业
        List<ForecastOpen> openCorpList = getOpenCorp(jdbcSession);
        for (ForecastOpen each : openCorpList) {
            if (each.getOpenNumber() == 0) {
                int pageSize = 100;
                JSONObject data = getAccount(doveClient, 1, pageSize, each.getCorpId());
                if (data != null) {
                    forecast(demandForecastService, data.getJSONArray("list"));

                    // 分页获取并处理
                    int totalPage = data.getIntValue("totalPage");
                    for (int i = 2; i <= totalPage; i++) {
                        data = getAccount(doveClient, i, pageSize, each.getCorpId());
                        forecast(demandForecastService, data.getJSONArray("list"));
                    }

                    // 统计
                    forecastStatisticsService.statistics();
                }
            } else if (each.getOpenNumber() > 0) {
                JSONObject data = getAccount(doveClient, 1, each.getOpenNumber(), each.getCorpId());
                if (data != null) {
                    forecast(demandForecastService, data.getJSONArray("list"));
                }
            }
        }

        return Result.success(openCorpList.size());
    }

    private static List<ForecastOpen> getOpenCorp(JdbcSession jdbcSession) {
        Timestamp now = new Timestamp(System.currentTimeMillis());
        return jdbcSession.findArray(ForecastOpen.class).eq("isOpen", 1).and().minEq("beginDate", now)
                .and().maxEq("endDate", now).exe(false);
    }

    private static void forecast(DemandForecastService demandForecastService, JSONArray list) throws Exception {
        for (Object each : list) {
            JSONObject account = (JSONObject) each;
            Map<String, DemandForecastTypeEnum> enumMap = DemandForecastTypeEnum.getEnumMap();
            for (Map.Entry<String, DemandForecastTypeEnum> entry : enumMap.entrySet()) {
                demandForecastService.forecast(account, entry.getValue());
            }
        }
    }

    private static JSONObject getAccount(DoveClient doveClient, int pageNo, int pageSize, String corpId) throws Exception {
        // 分页获取账号
        JSONObject accountResult = doveClient.post("/auth/account/service/getByCorpId", (http) -> {
            JSONObject body = new JSONObject();
            body.put("pageNo", pageNo);
            body.put("pageSize", pageSize);
            body.put("khtId", corpId);
            http.setBody(body.toJSONString());
        });
        return accountResult.getJSONObject("data");
    }

    public static boolean isForecastSwitch() {
        return forecastSwitch;
    }

    public static void setForecastSwitch(boolean forecastSwitch) {
        DemandForecastWorker.forecastSwitch = forecastSwitch;
    }
}
